#include "single.h"
#include "ui_single.h"

single::single(QTcpSocket* socket_single,const QString &itemText,QWidget *parent) :
    socket(socket_single), itemText(itemText),
    QWidget(parent),
    ui(new Ui::single)
{
    socket=socket_single;
    ui->setupUi(this);
    ui->iplabel->setText(itemText);
    file_sender = new fileclient;
     connect(socket,&QTcpSocket::readyRead,this,&single::dealClientRead);
}

single::~single()
{
    delete ui;
}

void single::setItemText(const QString &newText) {
    itemText = newText;
}

void single::dealClientRead()
{
    m_data.push_back(socket->readAll());
    quint16 len=(m_data[2]<<8&0xFF0)|static_cast<quint16>(m_data[1]);
    if(m_data.size()>=len)
    {
        QByteArray arr=m_data.mid(0,len);
        dealPack(arr);
        m_data=m_data.mid(len);
    }
}
void single::on_singlesendButton_clicked()
{
    char type=1;
    QByteArray OrignalMessage;
    if(m_filePath=="file")
    {
        OrignalMessage.append(ui->singlelineEdit->text());
        ui->singlelineEdit->clear();
        type=0x63;
    }
    else
    {
        if (m_filePath.isEmpty()) {
            // 未选择文件时的处理
            // ... 可以弹出消息框提醒用户选择文件
            QMessageBox::warning(this,"提示","请选择文件");
            qDebug()<<m_filePath.isEmpty();

        }
        else if(!m_filePath.isEmpty())
        {
            QFile file(m_filePath);
            qDebug()<<"file open"<<m_filePath;
            bool isopen=file.open(QIODevice::ReadOnly);
            if(!isopen) {
                // 文件打开失败的处理
                // ... 可以弹出消息框提醒用户文件无法打开
                QMessageBox::warning(this,"提示","文件打开失败");
                qDebug()<<isopen;
                return;
            }

            else if(isopen)
            {
                OrignalMessage = file.readAll();
                file.close();
                type=0x62;
            }
            m_filePath="file";
        }
    }
    quint16 l=OrignalMessage.size()+5;
    QByteArray sendbuffer;
    sendbuffer.append(0x66);
    sendbuffer.append(static_cast<char>(l&0x00FF));
    sendbuffer.append(static_cast<char>(l>>8&0x00FF));
    sendbuffer.append(0x03);
    sendbuffer.append(type);
    sendbuffer.append(OrignalMessage);
    socket->write(sendbuffer);
}
void single::selectFile()
{
    //file_sender->show();
       m_filePath = QFileDialog::getOpenFileName(this, tr("选择文件")); // 打开文件选择对话框
}
void single::dealPack(QByteArray b)
{
    extern User mainuser;
    // 引入实时时间和数据库
    QTime time = QTime::currentTime();
    QSqlQuery query(db);
   //拿到数据
    char cmd=b[3];
    char type=b[4];
    QByteArray arrdata=b.mid(5);
    do
    {
        if(cmd == 0x01)
        {
            break;
        }
        if(cmd == 0x02)
        {
            //我发的
            QString username = mainuser.getName();
            QString currenttime = time.toString("hh:mm:ss");
            QString data = ""+arrdata;
            QString info1 = QString("<b><font size='5' color='blue'>用户：%1 发送 [我] </font></b> <b><font size='4' color='grey'>%2 </font></b><br> <b><font size='4' color='black'>%3 </font></b><br>").arg(username,currenttime,data);
            if(type==0x63)
            {
                ui->singletextBrowser->append(info1);
            }
            QSound *soundEffect = new QSound(":/sound/send.wav");
            soundEffect->play();
            QString sqlinsert = QString("insert into allmessage values('%1',NULL,'%2','%3',1);").arg(username).arg(data).arg(time.toString("hh:mm:ss"));
            if(!query.exec(sqlinsert)){
                qDebug()<<"记录消息失败";
            }
            else
                qDebug()<<"记录消息成功";
        }
        if(cmd == 0x03)
        {
            //我收到的
            qDebug()<<m_filePath;
            if(type==0x63)
            {
                QString data = ""+arrdata;
                QString currenttime = time.toString("hh:mm:ss");
                QString info2 = QString("<b><font size='5' color='green'>用户：xxx 发送: </font></b> <b><font size='4' color='grey'>%1 </font></b><br> <b><font size='4' color='black'>%2 </font></b><br>").arg(currenttime,data);
                ui->singletextBrowser->append(info2);
                QSound *soundEffect = new QSound(":/sound/recieve.wav");
                soundEffect->play();
                QString sqlinsert = QString("insert into allmessage values(NULL,'%1','%2','%3',1);").arg(mainuser.getName()).arg(data).arg(time.toString("hh:mm:ss"));
                if(!query.exec(sqlinsert)){
                    qDebug()<<"记录消息失败";
                }
                else
                    qDebug()<<"记录消息成功";
            }
            else if(type==0x62)
            {
                qDebug()<<"接受文件";
                QString saveFilePath = QFileDialog::getSaveFileName(this, tr("保存文件")); // 打开文件保存对话框
                if (!saveFilePath.isEmpty())
                {
                    QFile file(saveFilePath);
                    if (file.open(QIODevice::WriteOnly))
                    {
                        file.write(arrdata);
                        file.close();
                        ui->singletextBrowser->append("接收到文件，并保存为：" + saveFilePath);
                    }
                    else
                    {
                        ui->singletextBrowser->append("保存文件失败");
                    }
                }
            }

        }
    }while(0);
}

void single::on_fileButton_clicked()
{
    selectFile();
}

